package com.itheima.controller;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.vo.UserQueryVO;
import javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("h","hello world from controller");
        return "hello";
    }

    /**
     * 支持LayUI + Thymeleaf模板 静态分页方式（类似JSP）
     * @param model
     * @return 模板目录下 hellouser.html 进行解析
     */
    @RequestMapping("/hellouser")
    public String hellouser(Model model){
        List<User> userList = new ArrayList<User>();
        for(Integer i = 0; i<1000; i++) {
            userList.add(new User(i,"Tom", i.toString(),new Date()));
            userList.add(new User(i,"Jerry", i.toString(),new Date()));
        }
        model.addAttribute("userlist",userList);
        return "hellouser";
    }


    @Autowired
    private UserService userService;

    /**
     * LayUI 动态表格数据 分页返回例子
     * @param page 显示页号
     * @param limit 每页的记录数
     * @return LayUI要求的
     */
    @GetMapping("/hellouser_json")
    @ResponseBody
    public Map<String, Object> hellouser_json(@RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "10") Integer limit){
        List<User> userList = userService.findAll();
        int total = userList.size();

        // 计算当前需要显示的数据下标起始值
        int startIndex = (page - 1) * limit;
        int endIndex = Math.min(startIndex + limit,total);

        List<User> pageList = userList.subList(startIndex,endIndex);
        Map<String, Object> resultMap = new HashMap<String, Object>();

        resultMap.put("code", 0);  //此处为0
        resultMap.put("msg", ""); //此处为空
        resultMap.put("count", userList.size());//此处放入总的数据数量
        resultMap.put("data", pageList); //此处应该放入实际页的数据
        return resultMap;
    }

    /**
     * 组合查询
     * @param userQueryVO 组合查询的条件
     * @return 组合查询的结果
     * @throws Exception 异常
     */
    @PostMapping("/users/search")
    @ResponseBody
    public Map<String, Object> searchList(UserQueryVO userQueryVO) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 200);
        resultMap.put("msg", "操作成功");
        resultMap.put("data", userService.listsearch(userQueryVO));
        resultMap.put("count", userService.listsearch(userQueryVO).size());//此处放入总的数据数量
        return resultMap;
    }

    /**
     * 新增用户
     * @param user 新增的用户信息
     * @return 返回新增的用户信息
     */
    @PostMapping("/users/add")
    @ResponseBody
    public Map<String, Object> addUser(User user){
        // 调新增方法（最好加一层判断该用户是否已存在，但是这个系统不晓得以什么为标准比较好）
        userService.addUser(user);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 200);
        resultMap.put("msg", "操作成功");
        resultMap.put("data", user);
        resultMap.put("count", 1);
        return resultMap;
    }

    /**
     * 根据 id 查询用户信息
     */
    @GetMapping("/users/getUserById/{id}")
    @ResponseBody
    public Map<String, Object> searchById(@PathVariable("id") Integer id){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 200);
        resultMap.put("msg", "操作成功");
        resultMap.put("data", userService.getUser(id));
        resultMap.put("count", 1);
        return resultMap;
    }

    /**
     * 根据 ID 编辑用户信息(ID已在user中)
     */
    @PostMapping("/users/updateById")
    @ResponseBody
    public Map<String, Object> updateById(User user) throws NotFoundException {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 200);
        resultMap.put("msg", "操作成功");
        resultMap.put("data", userService.updateById(user.getId(),user));
        resultMap.put("count", 1);
        return resultMap;
    }

    /**
     * 根据 ID 删除用户
     */
    @GetMapping("/users/{id}/delete")
    @ResponseBody
    public Map<String, Object> deleteById(@PathVariable Integer id){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        userService.deleteById(id);
        resultMap.put("code", 200);
        resultMap.put("msg", "操作成功");
        resultMap.put("data", "");
        resultMap.put("count", 1);
        return resultMap;
    }

    /**
     * 批量删除
     */
    @PostMapping("/users/deleteAll/{ids}")
    @ResponseBody
    public Map<String, Object> delAllUser(@PathVariable("ids") String ids){
        List<Integer> delList=new ArrayList<>();
        String[] strs=ids.split(",");
        for (String str:strs){
            userService.deleteById(Integer.valueOf(str));
            //优化，但有点问题，出在自定义dao中
            //delList.add(Integer.valueOf(str));
        }
        //userService.delAllUser(delList);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 200);
        resultMap.put("msg", "操作成功");
        resultMap.put("data", "");
        resultMap.put("count", 1);
        return resultMap;
    }
}
